package model

import (
	"gowork/dynamicCheckSheet/utils"
	"sync"
	"time"
)

type Paper struct {
	PaperId int64 `xorm:"pk autoincr"`
	PaperState int
	OrderId int64
	TotalPrice float64
	CheckNodeId int64
	RegionId int64
	RoleId int64
	CreatedAt time.Time
  	UpdatedAt time.Time
}

var plock sync.Mutex

func (p *Paper)Examination(pv *Paper) (map[string]interface{}, error){

	plock.Lock()

	var lpv Paper
	x.Where("paper_id = ? ", pv.PaperId).Get(&lpv)
	if lpv.PaperState != 1 {
		plock.Unlock()

		return map[string]interface{}{"message": "该记录已被审核","code":"400"}, nil
	}

	w := new(utils.Worker)

	pv.PaperState = 2
	x.Id(pv.PaperId).Update(pv)

	var cn *CheckNode
	currentNote := cn.QueryCheckNode(pv.CheckNodeId)

	nextNote := cn.QueryCheckNode(currentNote.NextCheckNodeId)

	if currentNote.NextCheckNodeId == 1{
		var ov Order
		ov.OrderState = 3
		x.Id(pv.OrderId).Update(ov)

		plock.Unlock()

		return map[string]interface{}{"message": "成功","code":"200"}, nil
	}

	var newPv = Paper{
		PaperId: w.GetId(),
		PaperState : 1,
		OrderId : pv.OrderId,
		TotalPrice : pv.TotalPrice,
		CheckNodeId : currentNote.NextCheckNodeId,
		RegionId : pv.RegionId,
		RoleId : nextNote.RoleId,
		CreatedAt : time.Now(),
		UpdatedAt : time.Now(),
	}
	x.Insert(&newPv)

	plock.Unlock()

	return map[string]interface{}{"message": "成功","code":"200"}, nil
}

func (p *Paper)QueryRolePaper(rId int64) ([]*Paper, error){
	var paperList []*Paper
	x.Where("role_id = ?", rId).Find(&paperList)
	return paperList, nil
}

func (p *Paper)QueryPaperList(cId int64) []*Paper{
	var pvList []*Paper
	x.Where("check_node_id = ?", cId).
		And("paper_state = ?", 1).Find(&pvList)
	return pvList
}

func (p *Paper)QueryPaperListByUserId(uId int64)([]*Paper, error){
	var pvList []*Paper
	x.Join("INNER", "check_node_user", "paper.check_node_id = check_node_user.check_node_id").
		Where("check_node_user.user_id = ?", uId).Find(&pvList)
	return pvList, nil
}

func (p *Paper)QueryRegionPaper(regionId int64)[]*Paper{
	var paperList []*Paper
	x.Where("region_id = ?", regionId).And("paper_state = ?", 1).Find(&paperList)
	return paperList
}
